package com.uziot.bucket;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.event.ContextRefreshedEvent;

import java.io.File;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author shidt
 * @version V1.0
 * @className EventApplication
 * @date 2020-12-15 11:02:07
 * @description 实现事件监控外部文件改变跟随，随后容器事件发布
 */

@Slf4j
@SpringBootApplication
public class EventApplication implements CommandLineRunner {
    @Autowired
    private ApplicationEventPublisher publisher;
    @Autowired
    private ApplicationContext applicationContext;
    private Long lastModified = 0L;
    private boolean instance = true;

    public static void main(String[] args) {
        SpringApplication.run(EventApplication.class, args);
    }

    @Override
    public void run(String... args) {
        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor(
                new ThreadFactoryBuilder().setNameFormat("properties read.").build()
        );
        executor.scheduleWithFixedDelay(this::publish, 0, 5, TimeUnit.SECONDS);
    }

    private void publish() {
        if (isPropertiesModified()) {
            log.info("文件改动，开始重新加载路由配置....");
            publisher.publishEvent(new ContextRefreshedEvent(applicationContext));
        } else {
            log.info("文件未改动，放弃加载.............");
        }
    }

    /**
     * 判定是否重新加载路由
     *
     * @return 是否
     */
    private boolean isPropertiesModified() {
/*        File file = new File(Objects.requireNonNull(this.getClass().getClassLoader()
                .getResource(PropertiesRouter.PROPERTIES_FILE)).getPath());*/
        File file = new File("E:\\router.properties");
        if (instance) {
            instance = false;
            return false;
        }
        if (file.lastModified() > lastModified) {
            lastModified = file.lastModified();
            return true;
        }
        return false;
    }


}
